<template>
  <div class='login'>
    <!--    导航条-->
    <van-nav-bar title='登录' />
    <!--    表单结构-->
    <van-form @submit='login'>
      <van-field
        required
        v-model='mobile'
        label='手机号'
        placeholder='请输入手机号'
        :rules='rules.mobile'
      />
      <van-field
        required
        v-model='code'
        type='number'
        label='验证码'
        placeholder='请输入验证码'
        :rules='rules.code'
      />
      <div style='margin: 16px;'>
        <van-button
          round block type='info'
          native-type='submit'
          :disabled='isLoad'
          :loading='isLoad'
          loading-text='加载中...'
        >提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
// import axios from '@/utils/request'
import { userLogin } from '@/api/user'
import { mapMutations } from 'vuex'

export default {
  name: 'Login',
  data () {
    return {
      isLoad: false,
      mobile: '13366669999',
      code: '246810',
      rules: {
        // 手机号的校验规则
        mobile: [
          {
            required: true,
            message: '手机号不能为空'
          },
          {
            pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '手机号码格式不正确',
            trigger: 'onBlur'
          }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      }
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    async login () {
      // 不能给提交按钮注册click来发送请求 ==> 如果不通过也会执行事件
      // console.log('登录进行中')
      this.isLoad = true
      try {
        const { data: res } = await userLogin(this.mobile, this.code)
        console.log(res)
        // console.log('登录成功')
        // 获取到登陆成功返回的token并存入vuex
        // this.$store.commit('user/setToken', res)
        // 使用辅助函数调用setToken
        this.setToken(res)
        this.$toast.success('登陆成功')
        // await this.$router.push('/user')
        // 不定死页面的写法
        const back = this.$route.query.back || '/user'
        // 获取flag的值 有就回退
        const flag = this.$route.query.flag
        console.log(this.$route)
        if (flag) {
          return this.$router.back()
        }
        await this.$router.push(back)
      } catch (e) {
        // console.log('登陆失败')
        this.$toast.fail('登陆失败')
      }

      this.isLoad = false
    }
  }
}
</script>

<style scoped>

</style>
